package org.afraid.freedns.api;

import java.util.Date;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.afraid.freedns.dto.UserDto;
import org.afraid.freedns.dto.UserLoginDto;
import org.afraid.freedns.exception.APIException;
import org.afraid.freedns.util.HttpClient;

import lombok.extern.slf4j.Slf4j;
import okhttp3.FormBody;
import okhttp3.FormBody.Builder;

/**
 * http://freedns.afraid.org
 * 
 * 代理调用解析工具类
 * 
 * @author jianggq
 * @date 2018年7月24日下午8:26:54
 */
@Slf4j
public class FreednsAPI {

	// 登录地址
	private static final String LOGIN_URL = "https://freedns.afraid.org/zc.php?step=2";

	// 用户信息地址
	private static final String PROFILE_URL = "http://freedns.afraid.org/profile/";

	// 解析表达式, 时间原因，这个表达式就直接复制了
	private static final String USERID_PATTERN = "UserID:</font></td><td bgcolor=#eeeeee><font face=\"verdana, Helvetica, Arial\" size=\"2\">(.*?)</font></td>";
	private static final String NAME_PATTERN = "Name:</font></td><td bgcolor=#eeeeee><font face=\"verdana, Helvetica, Arial\" size=\"2\">(.*?)</font></td>";
	private static final String EMAIL_PATTERN = "E-Mail:</font></td><td bgcolor=#eeeeee><a href=email.php><font face=\"verdana, Helvetica, Arial\" size=\"2\" color=\"black\">(.*?)</font></a>";

	/**
	 * 代理登录，并解析是否登录成功
	 * 
	 * 0：成功, 1：用户名或密码错误 2：其它异常
	 * 
	 * @param loginDto
	 * @return
	 */
	public static int login(UserLoginDto loginDto) {

		String html = null;

		try {

			// <input type="text" maxlength="255" size="16" name="username">
			// <input type="password" maxlength="16" size="16" name="password">
			// <input class="storeuserData" type="hidden" id="oPersistInput" name="remote">
			Builder formBody = new FormBody.Builder();
			formBody.add("username", loginDto.getEmail());
			formBody.add("password", loginDto.getPwd());
			formBody.add("remote", fnGenerateFingerPrint());
			formBody.add("action", "auth");

			html = HttpClient.post(LOGIN_URL, formBody);

			if (html.contains("Logged in as"))
				return 0; // 登录成功

			else if (html.contains("If you forget your password"))
				return 1; // 用户名或密码错误

			else {
				// 如果上面两个return 都没有拦住，这里打印日志方便跟踪
				log.info("Login Response：{}", html);
				throw new APIException("代理登录异常");
			}
		} catch (Exception e) {
			log.error("Login Error：{}", html);
			throw new APIException("代理登录异常", e); // 让全局异常去拦截，返回2
		}

	}

	/**
	 * 登录成功后代理获取用户信息
	 * 
	 * @return
	 */
	public static UserDto profile() {

		String html = null;

		try {

			html = HttpClient.get(PROFILE_URL);

			UserDto userDto = new UserDto();
			// userDto.setId(Long);
			userDto.setAccount(matcher(html, USERID_PATTERN, 1));
			userDto.setName(matcher(html, NAME_PATTERN, 1));
			// userDto.setPwd(String);
			userDto.setEmail(matcher(html, EMAIL_PATTERN, 1));

			Date nowDate = new Date();
			userDto.setUpdateTime(nowDate);
			userDto.setCreateTime(nowDate);

			return userDto;
		} catch (Exception e) {
			log.error("Profile Error：{}", html);
			throw new APIException("代理登录异常", e); // 让全局异常去拦截，返回2
		}
	}

	private static String fnGenerateFingerPrint() {
		String chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz!@#$%^&*()_+=-";
		int string_length = 64;
		String randomstring = "";
		for (int i = 0; i < string_length; i++) {
			int rnum = (int) Math.floor(Math.random() * chars.length());
			randomstring += chars.substring(rnum, rnum + 1);
		}
		return randomstring;
	}

	private static String matcher(String source, String pattern, int group) {

		// 创建 Pattern 对象
		Pattern r = Pattern.compile(pattern);

		// 现在创建 matcher 对象
		Matcher m = r.matcher(source);
		if (m.find()) {
			return m.group(group);
		}

		return "";
	}

	public static void main(String[] args) {

		try {
			UserLoginDto loginDto = new UserLoginDto();
			loginDto.setEmail("jgqwp@163.com");
			loginDto.setPwd("123456");

			int result = login(loginDto);

			log.info("result：{}", result);

			profile();

		} catch (Exception e) {
			// TODO: handle exception
			e.printStackTrace();
		}

	}
}
